<template>
    <el-container class="login-container">
        <el-form ref="formRef" class="login-form" :model="formModel" :rules="rules">
            <el-form-item label="账号" prop="name">
                <el-input v-model="formModel.name" />
            </el-form-item>
            <el-form-item label="密码" prop="pwd">
                <el-input v-model="formModel.pwd" />
            </el-form-item>
            <el-row justify="center">
                <el-button type="primary" @click="submitForm(formRef)">
                    登录
                </el-button>
                <el-button @click="reset(formRef)">重置</el-button>
            </el-row>
        </el-form>
    </el-container>
</template>
<script lang="ts" setup>
import { requestLogin } from '@/api/user/user';
import { ref } from 'vue';
import { useUserStore } from "@/stores/user"
import { ElMessage } from 'element-plus'
import { getUrlQuery } from '@/utils/common';
import { useRouter } from 'vue-router';
const router = useRouter();
const formModel = ref({
    name: "",
    pwd: "",
})
const rules = ref({
    name: [{ required: true, message: "请输入", trigger: "blur" }],
    pwd: [{ required: true, message: "请输入", trigger: "blur" }],
})
const formRef = ref();
const userStore = useUserStore();
const submitForm = async (formRef: any) => {
    if (!formRef) return
    let flag = true
    await formRef.validate((valid: any) => {
        if (!valid) {
            flag = false
        }
    })
    if (!flag) {
        return;
    }
    // loginRequest
    const userInfo = await requestLogin(formModel.value)
    if (!userInfo || !userInfo.access_token_code) {
        ElMessage({
            type: "error",
            message: "登录报错"
        })
        return;
    }
    userStore.setUserInfo(userInfo);
    const access_token_code = userInfo.access_token_code;
    const query = getUrlQuery();
    let tarHref;
    if (query.redirect) {
        tarHref = decodeURIComponent(query.redirect)
        if (tarHref.includes("?")) {
            tarHref += "&access_token_code=" + access_token_code;
        } else {
            tarHref += "?access_token_code=" + access_token_code;
        }
        location.href = tarHref;
    } else {
        router.push({
            path: "/home",
            query: {
                access_token_code
            }
        })
    }
}

const reset = (formRef: any) => {
    if (!formRef) return
    formRef.resetFields()
}
</script>
<style lang="scss" scoped>
.login-container {
    height: 100%;
    justify-content: center;
    align-items: center;

    .login-form {
        width: 500px;
    }
}
</style>